import React from 'react';
import { Spin, Alert } from 'antd';
import { useSetState } from 'ahooks';
import moment from 'moment';

import { TRAlert, TRDefault } from '#/components';
import renovate from '#/utils/renovate';
import { HttpCode } from '#/utils/contacts.js';

import { supplyRequest, getIssuedStatus, getDifference } from '../../service';
import { getCharts } from '../Charts/helper';
import TRtitle from '../TRtitle';
import Adjust from '../Adjust';
import Charts from '../Charts';
import { superToolShow, mergeSupplyData, subtract, fetchSupplyToolData } from './helper';
import styles from './index.less';

export default function Main({ dateValue, stationId, stationIds, isFresh, buttonPermissions }) {
  const TIMEFORMAT = 'YYYYMMDD';
  const TIMEFORMAT2 = 'YYYY-MM-DD';
  const [state, setState] = useSetState({
    rangeDate: [],
    selectRange: 0,
    selectExact: 0,
    supplyData: [],
    spinLoading: false,
    supplyTool: [],
    supplyDate: [],
    loading: false,
    beforeData: [],
  });

  React.useEffect(() => {
    timeInit();
  }, [JSON.stringify(dateValue), isFresh]);

  const fetchData = async (date, rangeValue) => {
    let [res, res1] = await Promise.all([
      supplyRequest({
        dataType: 0,
        endDate: date,
        isDefault: 0,
        startDate: date,
        stationId,
      }),
      getDifference({
        declareDate: moment(rangeValue).format(TIMEFORMAT2),
        gId: null,
        targetDate: date,
      }),
    ]);
    if (res?.statusCode === HttpCode.SUCCESS && res1?.statusCode === HttpCode.SUCCESS) {
      let _data = res?.supplyAndDemandAnalysisList || [];
      let supplyData = mergeSupplyData(_data, res1?.data || {});
      const newSuperTool = fetchSupplyToolData(supplyData);
      getToolData(newSuperTool);
      setState({
        beforeData: _data,
        supplyData,
        spinLoading: false,
        loading: false,
      });
    }
  };
  /* 供需分析toolTip展示 */
  const getToolData = (data) => {
    const list = nullValueJudgment(data);
    const useArr = getAdjustVolume(list);
    setState({
      supplyTool: useArr,
    });
  };

  const nullValueJudgment = (data) => {
    const arr = [
      {
        seriesName: '系统负荷-联络线',
        color: '#61F4F4',
      },
      {
        seriesName: '火电最小',
        color: '#048DE6',
      },
      {
        seriesName: '水电计划',
        color: '#61B1F4',
      },
      {
        seriesName: '新能源预测-DW',
        color: '#28B28B',
      },
      {
        seriesName: '调整后-出力预测',
        color: '#EC903B',
      },
    ];
    const list = [];
    const axisValueLabel =
      data.find((item) => {
        return item.axisValueLabel;
      })?.axisValueLabel || '';
    arr.forEach((item, index) => {
      let isInclude = data.find((i) => {
        return i.seriesName === item.seriesName;
      });
      if (isInclude) {
        list.push(isInclude);
      } else {
        list.push({
          ...item,
          value: '-',
          seriesIndex: index,
          seriesType: 'line',
          axisValueLabel,
        });
      }
    });
    return list;
  };

  /** 计算调整量 */
  const getAdjustVolume = (data) => {
    const tzclNumber =
      data.find((item) => {
        return item.seriesName === '调整后-出力预测';
      })?.value ?? '';
    const hdNumber =
      data.find((item) => {
        return item.seriesName === '火电最小';
      })?.value ?? '';
    const sdNumber =
      data.find((item) => {
        return item.seriesName === '水电计划';
      })?.value ?? '';
    const xnydwNumber =
      data.find((item) => {
        return item.seriesName === '新能源预测-DW';
      })?.value ?? '';
    const a = subtract(subtract(subtract(tzclNumber, hdNumber), sdNumber), xnydwNumber);
    const tzNumber =
      tzclNumber &&
      tzclNumber !== '-' &&
      hdNumber &&
      hdNumber !== '-' &&
      sdNumber &&
      sdNumber !== '-' &&
      xnydwNumber &&
      xnydwNumber !== '-'
        ? a
        : '-';
    const result = {
      seriesName: '调整量',
      value: tzNumber,
      seriesIndex: 5,
      seriesType: 'line',
    };
    return [...data, result];
  };

  const getIssuedData = async (date) => {
    let _date = moment(date).format(TIMEFORMAT2);
    let res = await getIssuedStatus(_date);
    if (res?.statusCode === HttpCode.SUCCESS) {
      fetchData(res?.data?.[0] || '', date);
      const dateArr = res?.data.map((item) => {
        return moment(item).format(TIMEFORMAT);
      });
      setState({
        supplyDate: dateArr,
      });
    }
  };
  /* 生成日期区间 */
  const timeInit = () => {
    if (!dateValue.length) return;
    setState({ spinLoading: true });
    const days = moment(dateValue[1]).diff(moment(dateValue[0]), 'days');
    let dateArr = new Array(days + 1).fill('');
    dateArr = dateArr.map((item, index) => {
      if (index == 0) {
        return moment(dateValue[0]).format(TIMEFORMAT);
      }
      return moment(dateValue[0]).add(index, 'day').format(TIMEFORMAT);
    });
    setState({ rangeDate: dateArr, selectRange: 0, selectExact: 0 });
    getIssuedData(dateArr?.[0]);
  };
  /* 切换 */
  const changeRangeFn = async (_index, key) => {
    if (renovate.isRenovate) {
      let obj = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
      if (obj.index === 1) {
        renovate.isRenovate = false;
        renovateDate(_index, key);
      }
    } else {
      renovateDate(_index, key);
    }
  };
  /* 切换日期 */
  const renovateDate = (_index, key) => {
    const { rangeDate = [], supplyDate = [], selectRange } = state;
    setState({ loading: true });
    if (key == 'selectRange') {
      // 切换申报日
      const date = rangeDate?.[_index];
      getIssuedData(date);
    } else {
      //切换标的日
      const date = supplyDate?.[_index];
      fetchData(moment(date).format(TIMEFORMAT2), rangeDate?.[selectRange]);
    }
    setState({
      [key]: _index,
      selectExact: key == 'selectRange' ? 0 : _index,
    });
  };

  const afterComputeFn = (data) => {
    let supplyData = mergeSupplyData(state.beforeData, data);
    setState({ supplyData });
  };
  /* render */
  const renderMain = () => {
    const { supplyData, supplyTool } = state;

    if (state.loading) {
      return (
        <div className={styles.loadingBox}>
          <Spin />
        </div>
      );
    }
    const isEmpty = supplyData?.every((item) => {
      return item?.list?.every((val) => !Number(val.value));
    });
    if (isEmpty) {
      return (
        <div className={styles.supplyBox}>
          <TRDefault type="emptysm" />
        </div>
      );
    }
    return (
      <div className={styles.supplyDiv}>
        <TRtitle title={'供需分析'} isShow />
        <div className={styles.chartsBox}>
          {superToolShow(supplyTool)}
          <Charts config={getCharts('SUPPLY_AND_DEMAND', supplyData, getToolData)} />
        </div>
      </div>
    );
  };

  const { selectExact, selectRange, loading, spinLoading, rangeDate, supplyDate } = state;
  if (spinLoading)
    return (
      <div className={styles.spinBox}>
        <Spin />
      </div>
    );
  if (!dateValue.length) {
    return (
      <div className={styles.emptyBox}>
        <TRDefault type="emptysm" />
        <div className={styles.message}>
          <Alert
            message={<span className={styles.spnColor}>请添加查询条件</span>}
            type="warning"
            showIcon
          />
        </div>
      </div>
    );
  }
  return (
    <div className={styles.container}>
      <div className={styles.containerTop}>
        {state.rangeDate.map((item, index) => (
          <span
            key={index}
            className={selectRange === index ? styles.topSelect : ''}
            onClick={() => changeRangeFn(index, 'selectRange')}
          >
            {item}
          </span>
        ))}
      </div>
      <div className={styles.rangeDate}>
        {state.supplyDate.map((item, index) => (
          <span
            key={index}
            className={selectExact === index ? styles.rangeSelect : ''}
            onClick={() => changeRangeFn(index, 'selectExact')}
          >
            {item}
          </span>
        ))}
      </div>
      {renderMain()}
      <Adjust
        rangeDate={rangeDate?.[selectRange] || ''}
        supplyDate={supplyDate?.[selectExact] || ''}
        stationIds={stationIds}
        loading={loading}
        afterComputeFn={afterComputeFn}
        isFresh={isFresh}
        buttonPermissions={buttonPermissions}
      />
    </div>
  );
}
